package com.zhike.service.file;

import java.io.File;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;

import javax.annotation.Resource;

import org.liuxp.minioplus.api.StorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zhike.common.conf.IMBaseConf;
import com.zhike.common.constant.Constants;
import com.zhike.common.constant.SysConfigConstants;
import com.zhike.common.enums.YesNoEnum;
import com.zhike.common.utils.AliSecurityCheckUtilsV1;
import com.zhike.service.system.ISystemConfigService;

import lombok.extern.slf4j.Slf4j;

/**
 * 语音留言消息中的音频文件上传处理实现类。
 * 
 * @author Json
 * @sin 2.0
 */
@Slf4j
@Component
public class MsgVoiceUploader extends UploaderRoot {

  @Resource
  private IMBaseConf baseConf;

  @Autowired
  private ISystemConfigService systemConfigService;

  @Autowired
  private AliSecurityCheckUtilsV1 apAliSecurityCheckUtilsV1;

  @Autowired
  private StorageService storageService;

  @Override
  public String getFileSaveDir() {
    return baseConf.getDIR_USER_UPLOAD();
  }

  @Override
  public void onUploadSucess(HashMap<String, Object> parametersFromClient) throws Exception {
    String userUid = (String) parametersFromClient.get("user_uid");
    // 因为服务端是支持多文件上传的API，所以客户端单独把文件名带过来了，方便使用！
    String fileName = (String) parametersFromClient.get("file_name");
    // // 客户端传过来的token，用于请求的合法性检查，当前未作强制检查，留作以后使用
    String url = (String) parametersFromClient.get("url");

    log.debug("[" + getDebugTAG() + "] " + fileName + "数据上传成功，马上处理其它业务逻辑...");

    Integer conf = systemConfigService.getValueByKeyAsInt(SysConfigConstants.CONFIG_TYPE_SECURITY,
        SysConfigConstants.CONFIG_MESSAGE);
    if (conf != null && conf.equals(YesNoEnum.NO.getValue())) {
      return;
    }

    // 客户端传过来的数据（参数）的合法性检查
    if (StringUtils.isNotBlank(userUid) && StringUtils.isNotBlank(fileName) && StringUtils.isNotBlank(url)) {
      if (!apAliSecurityCheckUtilsV1.checkVoice(url)) {
        storageService.remove(fileName);
        log.info("uid: {} 音频文件: {} 不合规 已删除", userUid, fileName);
        return;
      }
    } else {
      throw new Exception("[" + getDebugTAG() + "] 无效的参数：userUid=" + userUid + ", fileName=" + fileName + ".");
    }
  }

  @Override
  public void onUploadFailure(Exception ex) {
    log.error("[" + getDebugTAG() + "] 处理语音留言消息上传时出错了，" + ex.getMessage(), ex);
  }

  @Override
  public String getDebugTAG() {
    return "HTTP语音上传";
  }

  @Override
  public String getPathTag() {
    return Constants.UPLOAD_CHAT + "/voice";
  }

  @Override
  public Set<String> getDetectedTypes() {
    Set<String> allowExtensions = new HashSet<>();
    allowExtensions.add("txt");
    allowExtensions.add("pdf");
    allowExtensions.add("docx");
    return allowExtensions;
  }
}
